package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.oss.OssService;
import cc.linker.steplink.crm.merchanth5.dao.LiveGoodsDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LiveGoodsService {

    @Autowired
    private LiveGoodsDao liveGoodsDao;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private HttpService httpService;

    @Autowired
    private OssService ossService;

    @Value("${system.scrm.wxpushurl}")
    private String wxpushurl;

    @Value("${system.scrm.scrmWebUrl}")
    private String scrmWebUrlsv;

    @Value("${casclient.clientHost}")
    private String clientHostsv;
    @Autowired
    private MallDao mallDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Object getOrgList() {
        List<Map<String, Object>> orgList = liveGoodsDao.orgList();
        return orgList;
    }

    public void addStudio(Map<String, Object> params) {
        liveGoodsDao.addStudio(params);
    }

    public void updateStudio(Map<String, Object> params) {
        liveGoodsDao.updateStudio(params);
    }

    public void deleteStudio(Map<String, Object> params) {
        liveGoodsDao.deleteStudio(params);
    }

    public PageInfo getLiveGoodsList(Map<String, Object> params) {
        int pageIndex = 1, pageSize = 20;
        Object pi = params.get("pageIndex");
        if (pi instanceof Integer && (int) pi >= 0) {
            pageIndex = (int) pi;
        }
        Object ps = params.get("pageSize");
        if (ps instanceof Integer && (int) ps >= 0) {
            pageSize = (int) ps;
        }
        Integer customertype = liveGoodsDao.getCustomertype(params);
        params.put("customertype", customertype == null ? 1 : customertype);
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> goodsList = liveGoodsDao.getLiveGoodsList(params);
        return new PageInfo<>(goodsList);
    }

    public Object getStudioInfo(Map<String, Object> params) {
        if (params.get("studioId") != null && !"".equals(params.get("studioId").toString())) {
            Map<String, Object> studioInfo = liveGoodsDao.getStudioInfo(params);
            if (studioInfo == null) {
                throw GlobalException.build("无此直播间！");
            }
            return studioInfo;
        } else {
            throw GlobalException.build("参数错误！");
        }
    }

    public Object geth5LiveGoodsList(Map<String, Object> params) {
        List<Map<String, Object>> goodsList = liveGoodsDao.geth5LiveGoodsList(params);
        if (goodsList == null || goodsList.size() == 0) {
            goodsList = new ArrayList<>();
        }else {
            for(Map mallGoods: goodsList){
                if(!StringUtils.isEmpty(mallGoods.get("isSeckill")) && "1".equals(mallGoods.get("isSeckill").toString())){
                    this.getKillThings(mallGoods);
                }
            }
        }
        return goodsList;
    }

    public void getKillThings(Map mallGoods){
        try {
            Map<String, Object> seckillMap;
            String seckillMapStr = stringRedisTemplate.opsForValue().get("goodsSeckill:" + mallGoods.get("goodsId").toString());
            if (StringUtils.isEmpty(seckillMapStr)) {
                seckillMap =  mallDao.getSeckillByGoodsId(mallGoods.get("goodsId").toString());
                stringRedisTemplate.opsForValue().set("goodsSeckill:"  + mallGoods.get("goodsId").toString(), com.alibaba.fastjson.JSON.toJSONString(seckillMap, SerializerFeature.WriteMapNullValue),15, TimeUnit.SECONDS);
            }else {
                seckillMap = (Map<String, Object>) com.alibaba.fastjson.JSON.parse(seckillMapStr);
                SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                seckillMap.put("startTime",df2.format(new Date(Long.parseLong(seckillMap.get("startTime").toString()))));
                seckillMap.put("endTime",df2.format(new Date(Long.parseLong(seckillMap.get("endTime").toString()))));
            }
            if(seckillMap!=null && seckillMap.size()>0){
                String startTime = seckillMap.get("startTime").toString();
                String endTime = seckillMap.get("endTime").toString();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sd1=df.parse(startTime);
                Date sd2=df.parse(endTime);
                Date nowDate = new Date();
                mallGoods.put("seckillAllSecond",(sd2.getTime()-sd1.getTime())/1000);
                if(sd1.after(nowDate)){
                    //未开始
                    mallGoods.put("seckillStatus",0);
                    mallGoods.put("seckillSecond",(sd1.getTime()-nowDate.getTime())/1000);
                }else if(nowDate.after(sd2)){
                    //已结束
                    mallGoods.put("seckillStatus",2);
                    mallGoods.put("seckillSecond",(nowDate.getTime()-sd2.getTime())/1000);
                }else {
                    //进行中
                    mallGoods.put("seckillStatus",1);
                    mallGoods.put("seckillSecond",(sd2.getTime()-nowDate.getTime())/1000);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public Object getUrlList(String orgId) {
        List<Map<String, Object>> urlList = liveGoodsDao.getUrlList(orgId);
        return urlList;
    }

    public Object getuserInfo(String customerId) {
        Map<String, Object> userInfo = liveGoodsDao.getuserInfo(customerId);
        if (userInfo == null) {
            throw GlobalException.build("该用户不存在");
        }
        String qrcodeurl = "";
        try {
            String token = "";
            String pCustomerId = "";
            if (userInfo.get("token") != null) {
                token = userInfo.get("token").toString();
            }
            if (userInfo.get("customerId") != null) {
                pCustomerId = userInfo.get("customerId").toString();
            }
            if ("".equals(pCustomerId)) {
                Map<String, String> retMap = new HashMap<>();
                qrcodeurl = ossService.uploadFileToOssByUrl("https://open.weixin.qq.com/qr/code?username=" + token);
                userInfo.put("qrcodeurl", qrcodeurl);
            } else {
                String action = "getLimitQrcode";
                Map<String, String> param = new HashMap<>();
                param.put("token", token);
                param.put("action", action);
                param.put("val", pCustomerId);
                JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
                String result = httpService.doPost(wxpushurl, jsonObject.toJSONString());
                Object parse = JSON.parse(result);
                Map ret = (Map) parse;
                if (200 == (Integer) ret.get("errcode")) {
                    Map tmpMap = (Map) ret.get("data");
                    Map<String, String> res = new HashMap<>();
                    qrcodeurl = ossService.uploadFileToOssByUrl(tmpMap.get("qrcodeurl").toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        userInfo.put("qrcodeurl", qrcodeurl);
        return userInfo;
    }

    public Object getEndUrl(String studioId, String orgId, String clientHost, String scrmWebUrl) {
        String endurl = "";
        try {
            //String token = "gh_4a9194e05013";
            String token = liveGoodsDao.getoken(orgId);
            endurl = clientHost + "/personal/login?token=" + token + "&m="
                    + URLEncoder.encode(scrmWebUrl + "/userCenter.html?goto=" + URLEncoder.encode("live?studioId=" + studioId, "utf-8"), "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("endurl", endurl);
        return map;
    }

    public List<Map<String, Object>> getStudiolist(Map<String, Object> map) {
        List<Map<String, Object>> studioList = liveGoodsDao.studioList(map);
        return studioList;
    }

    /**
     * 创建直播间
     * params : account 手机号
     * params : iconUrl 头像
     * params : studioName 直播间名称
     * params : anchorDes 主持人简介
     * params : nickname 主持人昵称
     * params : type 1商家2大麦
     * params : studioId 直播间id（新增不传）
     * params : orgId
     * params : customerId
     */
    public Object saveStudio(Map<String, Object> params) {
        String url = systemProperties.getVideoUrl() + "thrid/saveThirdStud";
        String result = "";
        Map map = new HashMap();
        String account = "";
        String iconUrl = "";
        String studioName = "";
        String anchorDes = "";
        String nickname = "";
        String orgId = "";
        if (!StringUtils.isEmpty(params.get("account"))) {
            account = params.get("account").toString();
        }
        if (!StringUtils.isEmpty(params.get("iconUrl"))) {
            iconUrl = params.get("iconUrl").toString();
        }
        if (!StringUtils.isEmpty(params.get("studioName"))) {
            studioName = params.get("studioName").toString();
            nickname = params.get("studioName").toString();
            params.put("anchorName", studioName);
        }
        if (!StringUtils.isEmpty(params.get("anchorDes"))) {
            anchorDes = params.get("anchorDes").toString();
        }
        if (!StringUtils.isEmpty(params.get("orgId"))) {
            orgId = params.get("orgId").toString();
        }
        //查频道
        String broadcastId = liveGoodsDao.getbroadcastId(params);
        String token = liveGoodsDao.getoken(orgId);

        map.put("token", token);
        map.put("clientHost", clientHostsv);
        map.put("scrmWebUrl", scrmWebUrlsv);
        map.put("userPhone", account);
        map.put("studIcon", iconUrl);
        map.put("studName", studioName);
        map.put("userName", nickname);
        map.put("broadcastId", broadcastId);
        map.put("userDes", anchorDes);
        if (!StringUtils.isEmpty(params.get("studioId"))) {
            map.put("studId", params.get("studioId").toString());
        }
        JSONObject paramsObject = (JSONObject) JSONArray.toJSON(map);
        LOGGER.info("paramsObject------->" + paramsObject.toJSONString());
        try {
            result = httpService.doPost(url, paramsObject.toJSONString(), ContentConstant.JSON_HEADER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LOGGER.info("result---->" + result);
        //{"code":"200","msg":"创建账号成功！","adminUrl":"http://hdadmin.linker.cc/videoLivevAdmin/","account":"1861111221","password":"123456","downImageUrl":""}
        if (StringUtils.isEmpty(result)) {
            throw GlobalException.build("云观接口调用异常");
        }
        Map parse = (Map) com.alibaba.fastjson.JSON.parse(result);
        if (StringUtils.isEmpty(parse.get("code")) || !"200".equals(parse.get("code").toString())) {
            if (!StringUtils.isEmpty(parse.get("msg"))) {
                throw GlobalException.build(parse.get("msg").toString());
            }
            throw GlobalException.build("云观保存失败！");
        }
        params.put("type", 2);
        Map data = (Map) parse.get("data");
        if (!StringUtils.isEmpty(data.get("account"))) {
            account = data.get("account").toString();
            params.put("account", account);
        }
        String password = "";
        if (!StringUtils.isEmpty(data.get("password"))) {
            password = data.get("password").toString();
            params.put("password", password);
        }
        if (!StringUtils.isEmpty(data.get("watchliveUrl"))) {
            String watchliveUrl = data.get("watchliveUrl").toString();
            params.put("watchLiveUrl", watchliveUrl);
        }
        String studId = "";
        if (!StringUtils.isEmpty(data.get("studId"))) {
            studId = data.get("studId").toString();
            params.put("studId", studId);
        }
        if (!StringUtils.isEmpty(params.get("studioId"))) {
            //编辑
            liveGoodsDao.updateStudioNew(params);
        } else {
            //新增
            liveGoodsDao.addStudioNew(params);
        }
        Map resMap = new HashMap();
        resMap.put("studioId", studId);
        return resMap;
    }


    public String getAuthenticateState(Map<String, Object> params) {
        //先判断是否验证AUTHENTICATE_STATE
        String authenticateState = liveGoodsDao.getAuthenticateState(params);
        if (StringUtils.isEmpty(authenticateState)) {
            authenticateState = "0";
        }
        return authenticateState;
    }

    public Object getH5StudioInfo(Map<String, Object> params) {
        if (params.get("studioId") != null && !"".equals(params.get("studioId").toString())) {
            Map<String, Object> studioInfo = liveGoodsDao.getH5StudioInfo(params);
            if (studioInfo == null) {
                throw GlobalException.build("无此直播间！");
            }
            return studioInfo;
        } else {
            throw GlobalException.build("参数错误！");
        }
    }

    public Object getH5StudioAdminInfo(Map<String, Object> params) {
        Map<String, Object> StudioAdminInfo = liveGoodsDao.getH5StudioAdminInfo(params);
        return StudioAdminInfo;
    }

    public String getBindPhoneByCustomerId(String customerId) {
        return liveGoodsDao.getBindPhoneByCustomerId(customerId);
    }

    /**
     * nickName
     * bindPhone
     * orgId
     * customerId
     * logoUrl logo
     * iconUrl 头像
     * type 类型1机构2商家
     *
     * @param params
     * @return
     */
    public void openingStream(Map<String, Object> params) {
        // 开通频道
        Map<String, Object> channel = new HashMap<>();
        channel.put("sbroadcastingName", params.get("nickName"));
        channel.put("stepLinkOrgId", params.get("customerId"));
        channel.put("sbroadcastingLogo", params.get("logoUrl"));
        // 判断是否已经开通过
        int count = liveGoodsDao.ifOpenLive(params);
        if (count > 0) {
            throw GlobalException.build("开通出现问题，重复开通！");
        }
        String channelurl = systemProperties.getVideoUrl() + "/thrid/saveThridBroadcast";
        String broadcastId = "";
        try {
            String result = "";
            JSONObject channelJsonObject = (JSONObject) JSONArray.toJSON(channel);
            LOGGER.info("openingStream（开通频道）param：" + channelJsonObject.toJSONString());
            result = httpService.doPost(channelurl, channelJsonObject.toJSONString(), ContentConstant.JSON_HEADER);
            LOGGER.info("openingStream（开通频道）result：" + result);
            if (StringUtils.isEmpty(result)) {
                throw GlobalException.build("开通出现问题");
            }
            Map parse = (Map) com.alibaba.fastjson.JSON.parse(result);
            if (!StringUtils.isEmpty(parse.get("code")) && "200".equals(parse.get("code"))) {
                Map data = (Map) parse.get("data");
                broadcastId = data.get("broadcastId").toString();
            } else {
                throw GlobalException.build(parse.get("msg").toString());
            }
        } catch (Exception e) {
            throw GlobalException.build("开通出现问题");
        }

        // 开通频道管理员账号
        Map<String, Object> admin = new HashMap<>();
        admin.put("userPhone", params.get("bindPhone"));
        admin.put("userName", params.get("nickName"));
        admin.put("userIcon", params.get("iconUrl"));
        admin.put("broadcastId", broadcastId);

        String account = "";
        String password = "";
        String adminId = "";
        String adminurl = systemProperties.getVideoUrl() + "/thrid/saveThirdAccount";
        String result = "";
        try {
            JSONObject adminJsonObject = (JSONObject) JSONArray.toJSON(admin);
            LOGGER.info("openingStream（开通频道管理员）param：" + adminJsonObject.toJSONString());
            result = httpService.doPost(adminurl, adminJsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        } catch (Exception e) {
            throw GlobalException.build("开通出现问题。");
        }
        LOGGER.info("openingStream（开通频道管理员）result：" + result);
        if (StringUtils.isEmpty(result)) {
            throw GlobalException.build("开通出现问题!");
        }
        Map parse = (Map) com.alibaba.fastjson.JSON.parse(result);
        if (!StringUtils.isEmpty(parse.get("code")) && "200".equals(parse.get("code"))) {
            Map data = (Map) parse.get("data");
            account = data.get("account").toString();
            password = data.get("password").toString();
            adminId = data.get("adminId").toString();
        } else {
            throw GlobalException.build(parse.get("msg").toString());
        }
        // 入库 busi_shop_goods_studio_admin
        Map<String, Object> temp = new HashMap<>();
        temp.put("account", account);
        temp.put("password", password);
        temp.put("adminId", adminId);
        temp.put("iconUrl", params.get("iconUrl"));
        temp.put("nickName", params.get("nickName"));
        temp.put("broadcastId", broadcastId);
        temp.put("orgId", params.get("orgId"));
        temp.put("customerId", params.get("customerId"));
        temp.put("type", params.get("type"));
        LOGGER.info("insertStudioAdmin（插入频道表）：" + com.alibaba.fastjson.JSON.toJSONString(temp));
        liveGoodsDao.insertStudioAdmin(temp);
    }

    public Integer ifOpenLive(Map<String, Object> param) {
        return liveGoodsDao.ifOpenLive(param);
    }

    public String getNickNameByCustomerId(String customerId) {
        return liveGoodsDao.getNickNameByCustomerId(customerId);
    }

    public String getOrgNameByOrgId(String orgId) {
        return liveGoodsDao.getOrgNameByOrgId(orgId);
    }

    public String getBindPhoneByOrgId(String adminId) {
        return liveGoodsDao.getBindPhoneByOrgId(adminId);
    }

    public Integer getCheckStatus(Map<String, Object> params) {
        return liveGoodsDao.getCheckStatus(params);
    }

    /**
     * studId
     *
     * @param params
     */
    public void delLiveStream(Map<String, Object> params) {
        // 删除本地数据
        liveGoodsDao.delLiveStream(params);

        // 删除云观数据
        try {
            String result = "";
            Map<String, Object> param = new HashMap<>();
            param.put("studId", params.get("studioId"));
            JSONObject paramsObject = (JSONObject) JSONArray.toJSON(param);
            String url = systemProperties.getVideoUrl() + "/thrid/removeThirdStud";
            result = httpService.doPost(url, paramsObject.toJSONString(), ContentConstant.JSON_HEADER);
            if (StringUtils.isEmpty(result)) {
                throw GlobalException.build("删除失败");
            }
            Map parse = (Map) com.alibaba.fastjson.JSON.parse(result);
            if (StringUtils.isEmpty(parse.get("code")) || !"200".equals(parse.get("code"))) {
                throw GlobalException.build("删除失败");
            }
        } catch (Exception e) {
            throw GlobalException.build("删除失败");
        }
    }

    public int getSaleByCustomerId(String customerId) {
        return liveGoodsDao.getSaleByCustomerId(customerId);
    }

    public String getDeleteIds(Map<String, Object> params) {
        return liveGoodsDao.getDeleteIds(params);
    }

    //通过机构和账号获取直播间信息
    public Map<String, Object> getLiveInfoByAccount(String account, String orgId) {
        return liveGoodsDao.getLiveInfoByAccount(account, orgId);
    }

    public Object getOrgInfo(Map<String, Object> params) {
        Map<String, Object> orgInfo = liveGoodsDao.getOrgInfo(params);
        return orgInfo;
    }
}
